const app = getApp()
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const db = wx.cloud.database()
Page({
  data: {
    // motto: 'Hello World',
    list: [ "../../images/index/changshi.jpg","../../images/swiper/swiper1.jpg"],
    article: [],
    active: false,
    begin:false
  },
  toPages(e){
    // console.log(e.currentTarget.dataset.title)
wx.navigateTo({
  url: '/pages/artical/artical?title='+`${e.currentTarget.dataset.title}`,
})
  },
  start: function () {
    this.setData({
      active: true,
      begin:true
    })
    const options = {
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'PCM'
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      // console.log('recorder start')
      wx.showLoading({
        title: '录音中',
      })
    
    
    })
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    //  wx.hideLoading();
    })
  },
  //停止录音
  stop: function () {
    wx.hideLoading()
        //  console.log("你好啊")
    let that=this
    recorderManager.stop(() => {
    
    });
    //获取token
    var baiduyuyin = {
      apiKey: 'Tod0i5VO8SArILU2dMVdnAYR',
      secretKey: 'AEcOZ0t6dgIfxbFR6cynT9CKDGGVIEqx',
      url: 'https://openapi.baidu.com/oauth/2.0/token'
    };
    //获取token
    wx.request({
      url: baiduyuyin.url,
      data: {
        grant_type: 'client_credentials',
        client_id: baiduyuyin.apiKey,
        client_secret: baiduyuyin.secretKey
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        // console.log("你好啊")
       var baiduBccessToken=res.data.access_token
      //  console.log(baiduBccessToken)
        recorderManager.onStop((res) => {

          // console.log("你好")
          var tempFilePath = res.tempFilePath;//音频文件地址
          let myaudio = wx.createInnerAudioContext(); // 创建audio对象
myaudio.onError((res) => {
	// 播放音频失败的回调
	console.log(res)
})
myaudio.src = tempFilePath;  // 这里可以是录音的临时路径
myaudio.play();
          // var fileSize = res.fileSize;
          // console.log(tempFilePath)
          const fs = wx.getFileSystemManager();
          fs.readFile({//读取文件并转为ArrayBuffer
            filePath: tempFilePath,
            success(res) {
              const base64 = wx.arrayBufferToBase64(res.data);
              // console.log(base64)
              // console.log(base64)
              var fileSize = res.data.byteLength;
              // console.log(base64)
              wx.request({
                url: 'https://vop.baidu.com/server_api',
                data: {
                  format: 'pcm',
                  rate: 16000,
                  channel: 1,
                  cuid: 'sdfdfdfsfswww',
                  token: baiduBccessToken,
                  speech: base64,
                  len: fileSize
                },
                method: 'POST',
                header: {
                  'content-type': 'application/json' // 默认值
                },
                success(res) {
                // console.log(res)
                  that.setData({
                    active:false
                  })
                  var result = res.data.result[0];
                  result = result.substr(0, result.length - 1); 
                  console.log(result) 
                  // var keyword = result[0];
                  // keyword = keyword.replace("。", "");
                  wx.navigateTo({
                    url: '/pages/search/search?type=' + result
                  })
                }
              })
            }
          })
        })
      }
    })

  },
  //播放声音
  play: function () {
    // console.log("bo")
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })

  },
  toTextsearch() {
    // console.log("文字")
    wx.navigateTo({
      url: '../textsearch/textsearch'
    })
  },
  toPicturesearch() {
   
    wx.chooseMedia({
      count: 9,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
    }).then(res => {
      var base64 = wx.getFileSystemManager().readFileSync(res.tempFiles[0].tempFilePath, 'base64')
      // console.log(base64)
      // console.log(res)
      wx.showLoading({
        title: '加载中',
      })
      wx.request({
        url: 'https://api.tianapi.com/imglajifenlei/index',
        data:{key:"fd8e7e6160708c75e03c0529cef9096f",img:base64},
        header: {
            "content-type": "application/x-www-form-urlencoded"
        },
        method:"POST",
        success(res){
          console.log(res)
          wx.hideLoading()
          wx.navigateTo({
            url: '/pages/search2/search2?'+`data=${JSON.stringify(res.data.newslist)}`,
          })
        }


  })

    })
  },
  onLoad() {
    let that = this
    wx.cloud.callFunction({
      name: 'timer',
      data:{
      },
      success: function(res) {
      console.log(res)
      // that.setData({
      //   ArrayList:res.result.data
      // })
      }
    })
    // let that=this
    db.collection('artical')
    .get({
      success: function(res) {
        // res.data 是包含以上定义的两条记录的数组
        // console.log(res.data)
        that.setData({
          article:res.data
        })
      },
      
    })
    // wx.request({
    //   url: 'https://loshect.cn/findAll',
    //   success(res){
    //     // console.log(res.data)
    //     that.setData({
    //       article:res.data
    //     })
    //   }
    // })
  },
})